package servlet.user;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/getSongPathServlet")
public class GetSongPathServlet extends HttpServlet {
    private SongsService songsService = new SongsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取歌曲 ID
        String songIdStr = request.getParameter("songId");
        if (songIdStr == null || songIdStr.isEmpty()) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(Result.error("歌曲ID不能为空")));
            return;
        }

        int songId;
        try {
            songId = Integer.parseInt(songIdStr);
        } catch (NumberFormatException e) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(Result.error("歌曲ID格式不正确")));
            return;
        }

        // 获取歌曲路径
        String songPath = songsService.getSongPathById(songId);
        if (songPath == null) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(Result.error("歌曲路径不存在")));
            return;
        }

        // 返回歌曲路径
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(Result.success(songPath)));
    }
}
